import { getOssSigned, uploadFile, uploadToOss } from "@/api/photo";
import { ElNotification } from "element-plus";

export const debounce = function(func: Function, delay: number) {
  let timer:any = null
  return function() {
    const args = arguments
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
export const deepClone = function (obj: any) {
  if (Object.prototype.toString.call(obj) === "[object Array]") {
    return obj.map(deepClone);
  } else if (Object.prototype.toString.call(obj) === "[object Object]") {
    var cloned: any = {};
    // var keys = Object.keys(obj)
    var keys = Reflect.ownKeys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      cloned[key] = deepClone(obj[key]);
    }
    return cloned;
  } else {
    return obj;
  }
};

const config = { ENCRYPTION: true };
// 转码
export const Base64 = {
  encode: function (v: any) {
    return window.btoa(window.encodeURIComponent(v));
  },
  decode: function (v: any) {
    return window.decodeURIComponent(window.atob(v));
  },
};

export const _setLocalItem = function (key: string, value: any) {
  try {
    if (key === "" || key === undefined) {
      return;
    }
    if (key) {
      if (value == 0) {
        value = JSON.stringify(value);
        localStorage.setItem(
          config.ENCRYPTION ? Base64.encode(key) : key,
          value
        );
        return;
      }
      if (value === null || value === undefined || value === "") {
        return "";
      }
      // 编码
      let enObj = JSON.stringify(value);
      if (config.ENCRYPTION) {
        localStorage.setItem(Base64.encode(key), Base64.encode(enObj));
      } else {
        localStorage.setItem(key, enObj);
      }
    }
  } catch (err) {
    console.error(err);
  }
};
export const _removeLocalItem = function (key: string) {
  try {
    if (key === null || key === "" || key === undefined) {
      return "";
    }
    if (key) {
      localStorage.removeItem(key);
    }
  } catch (err) {
    console.error(err);
  }
};

export const _getLocalItem = function (key: string) {
  try {
    if (key === null || key === "" || key === undefined) {
      return "";
    }
    if (key) {
      let value = localStorage.getItem(
        config.ENCRYPTION ? Base64.encode(key) : key
      );
      if (value === null || value === undefined || value === "") {
        return "";
      } else {
        value = config.ENCRYPTION ? Base64.decode(value) : value;
        return JSON.parse(value);
      }
    }
  } catch (err) {
    console.error(err);
  }
};

// 使用 OSS 上传图片
export const uploadImageToOss = async (file: File, uploadType: number): Promise<any> => {
  return new Promise(async (resolve, reject) => {
    try {
      // 获取上传签名
      const ossSignedRes = await getOssSigned();
      const ossData = ossSignedRes.data;
      if (ossSignedRes.status != 200) {
        ElNotification.error({
          title: "Failed",
          message: "上传失败(预签名失败)",
          offset: 100,
        })
        reject("上传失败(预签名失败)");
      }

      const suffix = file.name.slice(file.name.lastIndexOf("."));
      const filename = Date.now() + suffix;
      const key = ossData.dir + "/" + filename;

      const formdata = new FormData();

      // 注意参数的顺序，key 必须是第一位，表示OSS存储文件的路径
      // formdata.append('key', 'photos/33.jpg') // photos:oss桶目录
      formdata.append("key", key); // photos:oss桶目录
      formdata.append("OSSAccessKeyId", ossData.accessId);
      formdata.append("policy", ossData.policy);
      formdata.append("signature", ossData.signature);
      // 文件上传成功默认返回 204 状态码，可根据需要修改为 200
      formdata.append("success_action_status", "200");
      // file 必须放在最后一位
      formdata.append("file", file);
      const dataUrl = ossData.host + "/" + key;
      const res = await uploadToOss(formdata, ossData.host);
      if (res && res.status && res.status == 200) {
        const { data } = await uploadFile({
          url: dataUrl,
          type: uploadType,
        });
        if (data && data === "上传成功") {
          resolve(dataUrl);
          ElNotification.success({
            title: "Success",
            message: "上传成功",
            offset: 100,
          })
        } else {
          ElNotification.error({
            title: "Failed",
            message: "上传到服务器失败",
            offset: 100,
          })
          reject("上传到服务器失败");
        }
      } else {
        ElNotification.error({
          title: "Failed",
          message: "上传到OSS失败",
          offset: 100,
        })
        reject("上传到OSS失败");
      }
    } catch (error:any) {
      ElNotification.error({
        title: "Failed",
        message: error.message,
        offset: 100,
      })
    }
  });
};

// cdn镜像源
export const cdnBaseHttp:string = "https://cdn.bootcss.com";

// external配置
export const externalConfig = [
  { name: "vue", scope: "Vue", js: "vue.min.js" },
  { name: "vue-router", scope: "VueRouter", js: "vue-router.min.js" },
  { name: "axios", scope: "axios", js: "axios.min.js" },
  {
    name: "element-ui",
    scope: "ELEMENT",
    js: "index.js",
    css: "theme-chalk/index.css",
  },
];

// 网站运行时间
export const getDay = () => {
  let startStamp = new Date("2023-10-23 13:00").getTime(); // 开始时间转化为时间戳
  let endStamp = new Date().getTime(); // 结束时间转化为时间戳
  let iDays = (endStamp - startStamp) / 1000 / 60 / 60 / 24; // 把相差的毫秒数转换为天数
  iDays = Number(iDays.toFixed(0)); // 保留一位小数
  console.log(iDays); // 输出结果
  return iDays;
};

// UTC时间传化为北京时间
export const utcToBeijing = function (utcTime: string) {
  // const utcDate = new Date(utcDateString);
  // const beijingDate = new Date(utcDate.getTime() + 8 * 60 * 60 * 1000);
  const beijingDate = new Date(utcTime)
  const year = beijingDate.getFullYear();
  const month = ("0" + (beijingDate.getMonth() + 1)).slice(-2); // 月份是从0开始的
  const day = ("0" + beijingDate.getDate()).slice(-2);
  const hours = ("0" + beijingDate.getHours()).slice(-2);
  const minutes = ("0" + beijingDate.getMinutes()).slice(-2);
  const seconds = ("0" + beijingDate.getSeconds()).slice(-2);

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

export const BaseUrl = location.host === "localhost:9567" ? "http://localhost:3000/" : "/api/" 

export const hasInjection = (htmlString: string) => {
  const scriptTagRegex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
  const maliciousCodeRegex = /(window|location|eval|setTimeout|setInterval|Function|document\.write|document\.writeln)/gi;
  const hasScriptTag = scriptTagRegex.test(htmlString);
  // 使用正则表达式检查HTML字符串中是否存在恶意JavaScript方法或属性
  const hasMaliciousCode = maliciousCodeRegex.test(htmlString);
  return hasScriptTag || hasMaliciousCode;
}

export const sanitizeHtmlString = (htmlString: string) => {
  const scriptTagRegex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
  const maliciousCodeRegex = /(window|location|eval|setTimeout|setInterval|Function|document\.write|document\.writeln)/gi;
  let sanitizedString = htmlString.replace(scriptTagRegex, '*');
  // 替换可能的恶意JavaScript方法或属性
  sanitizedString = sanitizedString.replace(maliciousCodeRegex, '*');
  return sanitizedString;
}
